package com.jason.core.config.security;

import com.alibaba.fastjson.JSONObject;
import com.jason.base.BaseProcess;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * jwt 未授权
 */
@Component
public class JwtAuthenticationEntryPoint extends BaseProcess implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        if (request.getMethod().toLowerCase().equals("options")){
        } else{
            Object result = null;
            if(authException instanceof BadCredentialsException){ /**身份认证未通过*/
                result = setForbiddenResult();
            }else{
                result = setUnAuthorizedResult();
            }
            response.getWriter().write(JSONObject.toJSONString(result));
            //InsufficientAuthenticationException
        }

    }
}
